package com.hejian.android.a72ggametools.utils;


import android.content.Context;
import android.os.Environment;
import android.util.Log;

import com.hejian.android.a72ggametools.impl.DownloadListener;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
 * Created by Administrator on 2016/1/9.
 */

public class GameDownloadUtils {

    private static final String TAG = "hejiandebug";
    String urlStr;
    String filePath;
    String fileName;

    DownloadListener downloadListener;

    public void setDownloadListener(DownloadListener listener) {
        this.downloadListener = listener;
    }

    public GameDownloadUtils(Context context, String url, String filePath,
                             String fileName) {
        this.urlStr = url;
        this.filePath = filePath;
        this.fileName = fileName;
    }

    public GameDownloadUtils(Context context, String url, String fileName) {
        this(context, url, "/download/", fileName);
    }

    public void start() {
        URL url = null;
        try {
            url = new URL(urlStr);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded;charset=utf-8");

            // 建立连接
            connection.connect();
            int length = connection.getContentLength();
            downloadListener.onStart(length);

            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {

                File path = Environment
                        .getExternalStoragePublicDirectory(filePath);
                File file = new File(path, fileName);
                BufferedInputStream is = new BufferedInputStream(
                        connection.getInputStream());
                BufferedOutputStream out = new BufferedOutputStream(
                        new FileOutputStream(file));
                byte[] buffer = new byte[10240];
                int len = 0;
                int receivedBytes = 0;
                mark:
                while(true)
                {
                    if(isPause) downloadListener.onPause();
                    if(isCancel) {
                        downloadListener.onCancel();
                        break mark;
                    }
                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    while (!isPause && (len = is.read(buffer)) > 0) {
                        out.write(buffer, 0, len);
                        receivedBytes += len;
                        downloadListener.onProgress(receivedBytes);
                        if(receivedBytes == length){
                            downloadListener.onSuccess(file);
                            break mark;
                        }
                        if(isCancel) {
                            downloadListener.onCancel();
                            file.delete();
                            break mark;
                        }
                    }
                }

                is.close();
                out.close();
            } else {
                Log.e(TAG, "ResponseCode:" + connection.getResponseCode()
                        + ", msg:" + connection.getResponseMessage());
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
            downloadListener.onFail();
        } catch (IOException e) {
            e.printStackTrace();
            downloadListener.onFail();
        }
    }

    private boolean isPause;

    public void pause() {
        isPause = true;
    }

    public void resume() {
        isPause = false;
        isCancel = false;
        downloadListener.onResume();
    }

    private boolean isCancel;
    public void cancel()
    {
        isCancel = true;
    }

}
